
import 'dart:async';
import 'dart:io';

import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/px_util.dart';
import 'package:nim_core/nim_core.dart';
import 'package:video_player/video_player.dart';

class VideoViewer extends StatefulWidget {
  const VideoViewer({Key key,  this.message}) : super(key: key);

  final NIMMessage message;

  @override
  State<StatefulWidget> createState() => _VideoViewerState();
}

class _VideoViewerState extends State<VideoViewer> {
   VideoPlayerController _controller;
  bool _progressShow = true;
  Timer _timer;

  void _playProgressAutoHide() {
    _timer?.cancel();
    if (_progressShow) {
      _timer = Timer(const Duration(seconds: 3), () {
        if (_progressShow) {
          setState(() {
            _progressShow = false;
          });
        }
      });
    }
  }

  @override
  void initState() {
    super.initState();
    NIMVideoAttachment attachment =
        widget.message.messageAttachment as NIMVideoAttachment;
    if((attachment?.path??'').isNotEmpty){
      _controller = VideoPlayerController.file(File(attachment?.path??''));
    }else{
      _controller = VideoPlayerController.network(attachment?.url??'');
    }

    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(false);
    _controller.initialize().then((_) {
      setState(() {});
    });
    _controller.play();
    _playProgressAutoHide();
  }

  @override
  void dispose() {
    _controller.dispose();
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(alignment: Alignment.bottomCenter, children: [
        Center(
          child: Hero(
            tag: '${widget.message.messageId}${widget.message.uuid}',
            child: _controller.value.isInitialized
                ? GestureDetector(
                    onTap: () {
                      setState(() {
                        _progressShow = !_progressShow;
                        _playProgressAutoHide();
                      });
                    },
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    ),
                  )
                : Container(),
          ),
        ),
        Visibility(
          visible: !_controller.value.isPlaying,
          child: GestureDetector(
            onTap: () {
              _controller.play();
            },
            child: Center(
              child: SvgPicture.asset(
                DrawableUtil.instance.ic_video_player,
                height: 80,
                width: 80,
              ),
            ),
          ),
        ),
        Positioned(
            left: 20,
            right: 20,
            bottom: 75,
            child: Visibility(
              visible: _progressShow,
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      if (_controller.value.isPlaying) {
                        _controller.pause();
                      } else {
                        _controller.play();
                      }
                    },
                    child: SvgPicture.asset(
                      _controller.value.isPlaying
                          ? DrawableUtil.instance.ic_video_pause
                          : DrawableUtil.instance.ic_video_resume,
                      height: 26,
                      width: 26,
                    ),
                  ),
                  const SizedBox(
                    width: 20,
                  ),
                  Text(
                    formatTimeMMSS(_controller.value.position.inSeconds),
                    style: const TextStyle(color: Colors.white, fontSize: 12),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: SizedBox(
                      height: 2,
                      child: VideoProgressIndicator(_controller,
                          colors: const VideoProgressColors(
                              playedColor: Colors.white,
                              backgroundColor: Color(0x4d000000)),
                          padding: EdgeInsets.zero,
                          allowScrubbing: false),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Text(
                    formatTimeMMSS(_controller.value.duration.inSeconds),
                    style: const TextStyle(color: Colors.white, fontSize: 12),
                  ),
                ],
              ),
            )),
        Positioned(
            right: PxUtil.instance.px_15,
            top: PxUtil.instance.statusBarHeight,
            child: GestureDetector(
              onTap: ()=>NavigatorUtil.goBack(),
              child: ImagesUtil.loadAssetImage(
                  DrawableUtil.instance.icon_room_close,
                width: PxUtil.instance.px_22
              ),
            )
        )
        // MediaBottomActionOverlay(widget.message)
      ]),
    );
  }
   String formatTimeMMSS(int time) {
     String mm = (time / 60).truncate().toString().padLeft(2, '0');
     String ss = (time % 60).toString().padLeft(2, '0');
     return '$mm:$ss';
   }
}
